<script setup lang="ts">
import { ref, onMounted, computed, Ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, ChatDotRound, Star, Plus } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { getDiscussionList, likeDiscussion, createDiscussion } from '@/api/discuss'

// 类型定义
interface Author {
  id?: string
  nickname?: string
  username?: string
  avatar?: string
}

interface Discussion {
  id: string
  title: string
  content: string
  category: string
  tags: string[]
  pub_date: string
  views: number
  likes: number
  comment_count: number
  author?: Author
  [key: string]: any
}

interface Pagination {
  page: number
  pageSize: number
  total: number
}

interface DiscussionForm {
  title: string
  content: string
  category: string
  tags: string[]
}

interface CategoryOption {
  label: string
  value: string
}

interface ApiResponse<T = any> {
  data: {
    code: string
    msg: string
    data?: T
  }
  status: number
}

interface DiscussionListResponse {
  list: Discussion[]
  pagination: Pagination
}

const router = useRouter()

// 响应式数据
const discussionList: Ref<Discussion[]> = ref([])
const loading: Ref<boolean> = ref(false)
const dialogVisible: Ref<boolean> = ref(false)
const formLoading: Ref<boolean> = ref(false)
const tagInput: Ref<string> = ref('')

// 表单数据
const discussionForm: Ref<DiscussionForm> = ref({
  title: '',
  content: '',
  category: '闲聊灌水',
  tags: []
})

// 分类选项
const categoryOptions: CategoryOption[] = [
  { label: '闲聊灌水', value: '闲聊灌水' },
  { label: '写作技巧', value: '写作技巧' },
  { label: '作品讨论', value: '作品讨论' },
  { label: '行业动态', value: '行业动态' },
  { label: '资源分享', value: '资源分享' }
]

const pagination: Ref<Pagination> = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 格式化时间显示
const formatTime = (timeString: string | undefined): string => {
  if (!timeString) return '未知时间'
  
  const date = new Date(timeString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 获取讨论列表
const fetchDiscussionList = async (): Promise<void> => {
  loading.value = true
  try {
    const response: ApiResponse<DiscussionListResponse> = await getDiscussionList({
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    })
    
    if (response.data.code === '0000') {
      discussionList.value = response.data.data?.list || []
      pagination.value.total = response.data.data?.pagination?.total || 0
    } else {
      const errorMsg = response.data.msg || '未知业务错误'
      ElMessage.error(`获取讨论列表失败: ${errorMsg}`)
    }
  } catch (error) {
    ElMessage.error('网络错误: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 打开创建讨论对话框
const openCreateDialog = (): void => {
  discussionForm.value = {
    title: '',
    content: '',
    category: '闲聊灌水',
    tags: []
  }
  tagInput.value = ''
  dialogVisible.value = true
}

// 处理标签输入
const handleTagInput = (): void => {
  if (tagInput.value && !discussionForm.value.tags.includes(tagInput.value) && discussionForm.value.tags.length < 5) {
    discussionForm.value.tags.push(tagInput.value)
    tagInput.value = ''
  }
}

// 移除标签
const removeTag = (index: number): void => {
  discussionForm.value.tags.splice(index, 1)
}

// 提交讨论
const submitDiscussion = async (): Promise<void> => {
  // 表单验证
  if (!discussionForm.value.title.trim()) {
    ElMessage.error('请输入讨论标题')
    return
  }
  
  if (!discussionForm.value.content.trim()) {
    ElMessage.error('请输入讨论内容')
    return
  }
  
  if (discussionForm.value.title.length > 100) {
    ElMessage.error('标题长度不能超过100个字符')
    return
  }
  
  if (discussionForm.value.content.length > 5000) {
    ElMessage.error('内容长度不能超过5000个字符')
    return
  }
  
  formLoading.value = true
  
  try {
    const response: ApiResponse = await createDiscussion({
      title: discussionForm.value.title.trim(),
      content: discussionForm.value.content.trim(),
      category: discussionForm.value.category,
      tags: discussionForm.value.tags
    })
    
    if (response.data.code === '0000') {
      ElMessage.success('讨论创建成功')
      dialogVisible.value = false
      pagination.value.page = 1
      await fetchDiscussionList()
    } else {
      ElMessage.error(response.data.msg || '创建讨论失败')
    }
  } catch (error) {
    ElMessage.error('创建讨论失败，请稍后重试')
  } finally {
    formLoading.value = false
  }
}

// 点赞讨论
const handleLike = async (discussion: Discussion): Promise<void> => {
  try {
    const response: ApiResponse = await likeDiscussion({ discussionId: discussion.id })
    
    if (response.data.code === '0000') {
      discussion.likes = response.data.data.likes
      ElMessage.success('点赞成功')
    } else {
      ElMessage.error(response.data.msg || '点赞失败')
    }
  } catch (error) {
    ElMessage.error('点赞失败，请稍后重试')
  }
}

// 查看讨论详情
const handleViewDetail = (discussion: Discussion): void => {
  router.push(`/discussion/${discussion.id}`)
}

// 评论讨论
const handleComment = (discussion: Discussion): void => {
  router.push(`/discussion/${discussion.id}#comments`)
}

// 分页处理
const handleSizeChange = (newSize: number): void => {
  pagination.value.pageSize = newSize
  pagination.value.page = 1
  fetchDiscussionList()
}

const handleCurrentChange = (newPage: number): void => {
  pagination.value.page = newPage
  fetchDiscussionList()
}

// 计算统计信息
const statistics = computed((): {
  totalDiscussions: number
  totalLikes: number
  totalComments: number
  totalViews: number
} => {
  return {
    totalDiscussions: pagination.value.total,
    totalLikes: discussionList.value.reduce((sum, item) => sum + (item.likes || 0), 0),
    totalComments: discussionList.value.reduce((sum, item) => sum + (item.comment_count || 0), 0),
    totalViews: discussionList.value.reduce((sum, item) => sum + (item.views || 0), 0)
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchDiscussionList()
})
</script>

<template>
  <PageContainer title="作家论坛">
    <template #extra>
      <el-button 
        type="primary" 
        :icon="Plus"
        @click="openCreateDialog"
      >
        发起讨论
      </el-button>
    </template>
    
    <div class="forum-container">
      <!-- 统计信息 -->
      <div class="statistics">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalDiscussions }}</div>
              <div class="stat-label">总讨论数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalLikes }}</div>
              <div class="stat-label">总点赞数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalComments }}</div>
              <div class="stat-label">总评论数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalViews }}</div>
              <div class="stat-label">总浏览数</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 讨论列表 -->
      <div class="discussion-list" v-loading="loading">
        <div 
          v-for="discussion in discussionList" 
          :key="discussion.id" 
          class="discussion-item"
        >
          <el-card shadow="hover" class="discussion-card">
            <template #header>
              <div class="discussion-header">
                <div class="author-info">
                  <el-avatar 
                    :src="discussion.author?.avatar" 
                    :size="40"
                    class="author-avatar"
                  >
                    {{ discussion.author?.nickname?.charAt(0) || discussion.author?.username?.charAt(0) || '?' }}
                  </el-avatar>
                  <div class="author-details">
                    <div class="author-name">{{ discussion.author?.nickname || discussion.author?.username || '未知用户' }}</div>
                    <div class="discussion-time">{{ formatTime(discussion.pub_date) }}</div>
                  </div>
                </div>
                <div class="discussion-category">
                  <el-tag 
                    :type="discussion.category === '写作技巧' ? 'success' : 
                           discussion.category === '作品讨论' ? 'warning' : 
                           discussion.category === '行业动态' ? 'danger' : 'info'"
                  >
                    {{ discussion.category || '未分类' }}
                  </el-tag>
                </div>
              </div>
            </template>

            <div class="discussion-content">
              <h3 class="discussion-title" @click="handleViewDetail(discussion)">
                {{ discussion.title || '无标题' }}
              </h3>
              <p class="discussion-text">{{ discussion.content || '无内容' }}</p>
              
              <!-- 标签 -->
              <div class="discussion-tags" v-if="discussion.tags && discussion.tags.length > 0">
                <el-tag
                  v-for="tag in discussion.tags.slice(0, 3)"
                  :key="tag"
                  size="small"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="discussion.tags.length > 3" class="more-tags">+{{ discussion.tags.length - 3 }}</span>
              </div>
            </div>

            <template #footer>
              <div class="discussion-footer">
                <div class="discussion-stats">
                  <span class="stat-item">
                    <el-icon><View /></el-icon>
                    {{ discussion.views || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ discussion.comment_count || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ discussion.likes || 0 }}
                  </span>
                </div>
                <div class="discussion-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :icon="Star"
                    @click="handleLike(discussion)"
                  >
                    点赞
                  </el-button>
                  <el-button 
                    type="success" 
                    size="small" 
                    :icon="ChatDotRound"
                    @click="handleComment(discussion)"
                  >
                    评论
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small" 
                    :icon="View"
                    @click="handleViewDetail(discussion)"
                  >
                    详情
                  </el-button>
                </div>
              </div>
            </template>
          </el-card>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && discussionList.length === 0" class="empty-state">
          <el-empty description="暂无讨论内容" :image-size="150" />
          <p class="empty-tip">还没有人发布讨论，快来发表第一个讨论吧！</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建讨论对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="发起讨论"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="discussionForm" 
        label-width="80px"
        :rules="{
          title: [
            { required: true, message: '请输入讨论标题', trigger: 'blur' },
            { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入讨论内容', trigger: 'blur' },
            { min: 1, max: 5000, message: '内容长度在 1 到 5000 个字符', trigger: 'blur' }
          ]
        }"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="discussionForm.title"
            placeholder="请输入讨论标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="discussionForm.category" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="discussionForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入讨论内容"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="标签">
          <div class="tags-container">
            <el-tag
              v-for="(tag, index) in discussionForm.tags"
              :key="tag"
              closable
              @close="removeTag(index)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="discussionForm.tags.length < 5"
              v-model="tagInput"
              size="small"
              placeholder="输入标签后按回车"
              @keyup.enter="handleTagInput"
              @blur="handleTagInput"
              class="tag-input"
            />
          </div>
          <div class="tag-tip">最多可添加5个标签，按回车确认</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          :loading="formLoading"
          @click="submitDiscussion"
        >
          发布讨论
        </el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<style scoped>
.forum-container {
  padding: 20px;
}

.statistics {
  margin-bottom: 30px;
}

.stat-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
}

.discussion-list {
  min-height: 400px;
}

.discussion-item {
  margin-bottom: 20px;
}

.discussion-card {
  transition: all 0.3s ease;
}

.discussion-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.discussion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-avatar {
  margin-right: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.discussion-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.discussion-content {
  margin: 16px 0;
}

.discussion-title {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
  margin: 0 0 12px 0;
  cursor: pointer;
  transition: color 0.3s;
}

.discussion-title:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.discussion-text {
  color: #666;
  line-height: 1.6;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.discussion-tags {
  margin-top: 12px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 4px;
}

.more-tags {
  font-size: 12px;
  color: #999;
}

.discussion-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.discussion-stats {
  display: flex;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  color: #666;
  font-size: 14px;
}

.stat-item .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.discussion-actions .el-button {
  margin-left: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-tip {
  margin-top: 16px;
  color: #999;
  font-size: 14px;
}

/* 标签样式 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.tag-input {
  width: 120px;
}

.tag-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .discussion-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .author-info {
    margin-bottom: 12px;
  }
  
  .discussion-footer {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .discussion-stats {
    margin-bottom: 12px;
  }
  
  .statistics .el-col {
    margin-bottom: 16px;
  }
}
</style>